const BaseController = require("./base/base");
const Result = require("../utils/result");
const ordersModel = require("../model/orders");
const cartModel = require("../model/cart");
const { getTokenUser, isAdmin } = require("../middlewares/auth");
class OrdersController extends BaseController {
  constructor() {
    super();
  }
  getAll(req, res, next) {
    setTimeout(async () => {
      try {
        let { user_id, role: isadmin = "" } = getTokenUser(req);
        if (isAdmin(isadmin)) user_id = null;
        let { pagesize = 10, page = 1, } = req.query;
        if (!pagesize) pagesize = 10;
        if (!page) page = 1;
        let count = await ordersModel.getCount({ ...req.query, pagesize, page, user_id });
        let ret = await ordersModel.getAll({ ...req.query, pagesize, page, user_id });
        res.json(Result.ok("success", { total: count[0].count, list: ret }));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  getAllList(req, res, next) {
    setTimeout(async () => {
      try {
        let { user_id, role: isadmin = "" } = getTokenUser(req);
        if (isAdmin(isadmin)) user_id = null;
        let { pagesize = 10, page = 1, } = req.query;
        if (!pagesize) pagesize = 10;
        if (!page) page = 1;
        let count = await ordersModel.getCount({ ...req.query, pagesize, page, user_id });
        let ret = await ordersModel.getAll({ ...req.query, pagesize, page, user_id });
        ret.forEach(async order => {
          let dret = await ordersModel.queryDetail(order.order_id);
          order.data = dret;
        });
        setTimeout(() => {
          res.json(Result.ok("success", { total: count[0].count, list: ret }));
        }, 300)
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  insert(req, res, next) {
    setTimeout(async () => {
      try {
        let { user_id: userid } = getTokenUser(req);
        let { user_id, sjr, sjdz, tel, total_money, data } = req.body;
        if (!user_id || user_id != userid) return res.json(Result.fail("用户ID有误,数据篡改"));
        if (!sjr || !sjdz || !tel || !total_money || !data) return res.json(Result.fail("sjr, sjdz, tel, total_money, data 参数必填"));
        if (typeof data != 'object') data = JSON.parse(data) || [];
        let order_no = 'I' + new Date().getTime() + "" + (Math.round(Math.random() * (99999 - 10000)) + 10000)
        let ret = await ordersModel.insert({ user_id, sjr, sjdz, tel, total_money, order_no, status: '待支付' });

        data.forEach(od => {
          let { goods_id, goods_num: cart_num, total } = od;
          let obj = { order_id: ret.insertId, goods_id, cart_num, total };
          ordersModel.insertDetail(obj);
          cartModel.delById(user_id, goods_id);
        });


        !ret.insertId ?
          res.json(Result.fail("添加失败", ret)) :
          res.json(Result.ok("添加成功", ret));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  update(req, res, next) {
    setTimeout(async () => {
      try {
        let { user_id, role: isadmin = "" } = getTokenUser(req);
        // if (!isAdmin(isadmin)) user_id = userid;//不是管理员只能修改自己的
        const { id } = req.params;
        delete req.body.total_money; //不允许修改价格字段
        let ret = await ordersModel.update({ ...req.body }, id);
        !ret.affectedRows ?
          res.json(Result.fail("修改失败", ret)) :
          res.json(Result.ok("修改成功", ret));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  queryDetail(req, res, next) {
    setTimeout(async () => {
      try {
        let { user_id: userid, role: isadmin = "" } = getTokenUser(req);
        let { user_id } = req.query;
        if (!isAdmin(isadmin)) user_id = userid;//不是管理员只能查自己的
        const { id } = req.params;  //order_id
        let ret = await ordersModel.queryDetail(id, user_id);
        res.json(Result.ok("success", ret));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
}
module.exports = new OrdersController().resolve();